package util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录地址过滤
 * @author ljldn
 *
 */
public class RemoteFilter implements Filter{

	private FilterConfig fc;
	@Override
	public void init(FilterConfig filterconfig) throws ServletException {
		// TODO Auto-generated method stub
		fc=filterconfig;
	}

	@Override
	public void doFilter(ServletRequest servletrequest,
			ServletResponse servletresponse, FilterChain filterchain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		//获取初始化参数
		String access = fc.getInitParameter("access");
		//获取服务端地址
		String local = servletrequest.getLocalAddr();
		//获取客户端地址
		String remote = servletrequest.getRemoteAddr();
		String remoteAddr =  getIpAddr((HttpServletRequest)servletrequest);
		HttpServletResponse resp = (HttpServletResponse)servletresponse;
		//System.out.println("remote："+remoteAddr);
		//System.out.println("local:"+local);
		if(null != access && "true".equals(access)){
			filterchain.doFilter(servletrequest, servletresponse);
		}else if(!"0:0:0:0:0:0:0:1".equals(remoteAddr)&&!"127.0.0.1".equals(remoteAddr)&&!remoteAddr.equals(local)){
			//客户端地址不是0:0:0:0:0:0:0:1 ,127.0.0.1,并且服务端地址 !=客户端地址，非法访问
			//servletresponse.getWriter().print("<script type='text/javascript'>");
			//servletresponse.getWriter().print("alert('非法访问');");
			//servletresponse.getWriter().print("</script>");
			//servletrequest.getRequestDispatcher("index.jsp").forward(servletrequest, servletresponse);
			//resp.sendRedirect("http:///www.baidu.com");
			filterchain.doFilter(servletrequest, servletresponse);
			return;
		}else{
			filterchain.doFilter(servletrequest, servletresponse);
		}
		filterchain.doFilter(servletrequest, servletresponse);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
	/**
	 * 获取客户端地址：
	 * 1.通过'x-forwarded-for、Proxy-Client-IP、WL-Proxy-Client-IP'，依次获取客户端地址
	 * 2.当客户端为本地地址时，将0.0.0.0.0.0.0.1或127.0.0.1通过InetAddress对象getHostAddress()方法获取网卡地址
	 * 3.通过多个代理获取多个ip时，多个ip通过逗号分隔，第一个地址为真实地址
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    } 

}
